package leetcode_301_400;

import java.time.chrono.IsoChronology;
import java.util.Stack;

public class LeeCode_331 {
    public static void main(String[] args) {
//        System.out.println(isValidSerialization2("9,3,4,#,#,1,#,#,2,#,6,#,#"));
        System.out.println(isValidSerialization2("1,#,#"));
    }

    private static boolean isValidSerialization2(String preorder) {
        Stack<Integer> stack = new Stack<>();
        String[] split = preorder.split(",");
        stack.push(1);
        for (String s : split) {
            if (s.length() == 0)
                return false;
            Integer peek = stack.peek();
            if (peek == 0)
                stack.pop();
            if (stack.size() == 0){
                return false;
            }
            if (s.equals("#")) {
                Integer pop = stack.pop();
                stack.push(pop - 1);
            }else {
                Integer pop = stack.pop();
                stack.push(pop + 1);
            }
        }
        while (stack.size() != 0 && stack.peek() == 0)
            stack.pop();
        return stack.size() == 0;
    }

    private static boolean isValidSerialization(String preorder) {
        int len = preorder.length();
        int i = 0;
        int slots = 1;
        while (i < len) {
            if (slots == 0)
                return false;
            if (preorder.charAt(i) == ',') {
                i++;
            } else if (preorder.charAt(i) == '#') {
                slots--;
                i++;
            } else {
                while (i < len && preorder.charAt(i) != ',') {
                    i++;
                }
                slots++;
            }
        }
        return slots == 0;
    }
}
